package com.spdd.mt.biz.manager.service;

import com.spdd.mt.biz.config.ConfigBean;
import com.spdd.mt.biz.constant.OrderStatus;
import com.spdd.mt.biz.entity.MtRechargeOrderEntity;
import com.spdd.mt.biz.service.MtRechargeOrderService;
import com.spdd.mt.common.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 生成对账文件服务
 *
 * @since 2025年04月08日
 */
@Slf4j
@Service
public class BatchService {

    @Autowired
    private MtRechargeOrderService rechargeService;

    @Autowired
    private ConfigBean configBean;

    private static final Map<Integer, Integer> statusMap;

    static {
        statusMap = new HashMap<>();
        statusMap.put(OrderStatus.SUCCESS.getValue(), 1);
        statusMap.put(OrderStatus.REEXCHANGE.getValue(), 2);
    }

    public boolean createFile(String date) {
        log.info("开始生成对账文件");
        try {
            for (String appId : configBean.getAppIds()) {
                log.info("查询appId:{}的数据", appId);
                // 对账文件是根据终态日期筛选数据，存在跨月的情况，所以先查询上一个月的数据
                List<MtRechargeOrderEntity> list = new ArrayList<>();
                list.addAll(rechargeService.getFinishByDayAndMerchNo(DateUtils.getLastMonth(), Integer.valueOf(date), appId));
                // 再查询本月的数据
                list.addAll(rechargeService.getFinishByDayAndMerchNo(date.substring(0, 6), Integer.valueOf(date), appId));
                log.info("查询appId:{}在{}的数据量为:{}", appId, date, list.size());
                log.info("开始写入文件");
                StringBuilder head = new StringBuilder();
                head.append("字节订单号").append(",")
                        .append("供应商/运营商订单号").append(",")
                        .append("供应商/运营商商⼾号(appid)").append(",")
                        .append("订单提交时间").append(",")
                        .append("订单终态时间").append(",")
                        .append("产品⾯额(分)").append(",")
                        .append("产品实付价格（分）").append(",")
                        .append("订单状态").append(",")
                        .append("备注（可选）").append("\r\n");
                StringBuilder body = new StringBuilder();
                list.forEach(entity -> {
                    // String timeDate = DateUtils.getDateTimeByTimestamp(entity.getTimestamp());
                    // if (StringUtils.isBlank(timeDate)) {
                    //     timeDate = ""; // DateUtils.getDateTimeByDate(entity.getCreateTime());
                    // }
                    // OrderStatus orderStatus = OrderStatus.findByValue(entity.getOrderStatus());
                    // String status = "";
                    // if (Objects.nonNull(orderStatus)) {
                    //     status = orderStatus.getDesc();
                    // }

                    body.append(entity.getMerchNo()).append(",")
                            .append(entity.getMtOrderNo()).append(",")
                            .append(entity.getOrderNo()).append(",")
                            .append(getPrice(entity.getContractPrice(), entity.getOrderStatus())).append(",")
                            .append(statusMap.getOrDefault(entity.getOrderStatus(), 1)).append(",")
                            .append(DateUtils.formatPureDateTime(entity.getStartTime())).append(",")
                            .append(DateUtils.formatPureDateTime(entity.getFinishTime()))
                            .append("\r\n");
                });
                Path directoryPath = Paths.get(configBean.getCreateFilePath());
                Path filePath = directoryPath.resolve(appId + "_" + date + ".csv");
                try {
                    Files.createDirectories(directoryPath);
                    Files.write(filePath, head.append(body).toString().getBytes(StandardCharsets.UTF_8));
                } catch (IOException ie) {
                    log.error("appId{}写入文件失败", appId, ie);
                }
            }

            return true;
        } catch (Exception e) {
            log.error("生成对账文件异常", e);
            return false;
        }
    }

    private String getPrice(String price, Integer orderStatus) {
        if (OrderStatus.REEXCHANGE.getValue().equals(orderStatus)) {
            return "-" + price;
        }
        return price;
    }
}
